import React, { Component } from 'react';
import Taro, { Config, getCurrentInstance } from '@tarojs/taro';
import { ScrollView, View, Image, Text, Input } from '@tarojs/components'
import { AtButton, AtMessage, AtInputNumber } from 'taro-ui'
import CarInfo from '@/components/CarInfo'
import Iconfont from '@/components/Iconfont'
import classnames from 'classnames'
import './index.scss'
import { fetchSetDefault, fetchDel } from '@/api/car'
import { delayQuerySelector, uuid } from '@/utils'
import { getDiySpecList, getDiySpecUseList } from '@/api/annual'
import qs from 'qs'

import { connect } from 'react-redux'
import { upDatedDiyCategory } from '@/store/annual/action'

type State = {
  disabled: boolean
  navIndex: number
  scrollTop: number
  goodsList: Array<any>
  form: any
}

@connect<any>(({ annual }) => ({ annual }), _dispatch => ({
  dispatchDiyList(data) {
    return _dispatch(upDatedDiyCategory(data))
  }
}))

export default class AnnualDiySpecIndex extends Component<any, State> {
  $instance = getCurrentInstance();
  protected bannerH: number
  protected bannerImg: string = `${SOURCES_PATH}/img/annual/banner.png`
  protected cartImg: string = `${SOURCES_PATH}/img/annual/cart.png`
  protected params: any
  protected goodsId: number | string
  constructor() {
    super(...arguments)
    this.state = {
      disabled: true,
      navIndex: 0,
      scrollTop: 0,
      goodsList: [],
      form: {
        items: 2
      }
    }
  }
  static options = {
    addGlobalClass: true
  }

  handleClick(item) {
    Taro.navigateTo({
      url: `/pages/detection/detail/index?reportId=${item.reportId}&title=${item.typeLabel}`
    })
  }
  onScroll(e) {

  }

  UNSAFE_componentWillMount() {
    delayQuerySelector(this, '.banner-wrap', 0).then(rect => {
      if (rect[0]) {
        this.bannerH = rect[0].height
      }
    })
  }

  componentDidMount() {
    const { params } = this.$instance.router
    this.params = params
    this.getDiyListByCarId(params)
  }

  async getDiyListByCarId(params: any) {

    let { carModelMatchType, categoryCode, jekunModelCode } = params
    Taro.showLoading({title: '加载中'})
    try {
      let res = await getDiySpecList({
        query: {
          filter: {
            and: []
          }
        },
        carModelMatchType,
        categoryCode,
        jekunModelCode
      })
      if (res.data.success) {
        let goodsList = this.forMatData(res.data.data)
        this.setState({
          goodsList
        })
      }
    } catch (error) {

    } finally {
      Taro.hideLoading()
    }
  }

  forMatData(data) {
    data = data.map((i, index) => {
      return {
        ...i,
        checked: false
      }
    })
    return data
  }

  handleChecked(index) {
    let { goodsList } = this.state
    goodsList = goodsList.map((i) => {
      return {
        ...i,
        checked: false
      }
    })
    goodsList[index].checked = true
    this.goodsId = goodsList[index].goodsId
    this.setState({
      goodsList,
      disabled: false
    })
  }

  handleSubmit(e) {
    const { disabled } = this.state
    const { carModelMatchType } = this.params
    if (!disabled) {
      if (+carModelMatchType === 2) {
        this.getDiySpecUseList()
      } else if (+carModelMatchType === 3) {
        Taro.navigateTo({
          url: `/pages/annual/diySpecNum/index?${qs.stringify({
            goodsId: this.goodsId,
            jekunModelCode: this.params.jekunModelCode,
            categoryCode: this.params.categoryCode,
            categoryKey: this.params.categoryKey,
            parentKey: this.params.parentKey,
            carModelMatchType: this.params.carModelMatchType
          })}`
        })
      }

    }
  }

  async getDiySpecUseList() {
    let { carModelMatchType, categoryCode, jekunModelCode, categoryKey, parentKey } = this.params
    Taro.showLoading({title: '加载中'})
    try {
      let res = await getDiySpecUseList({
        query: {
          filter: {
            and: []
          }
        },
        goodsId: this.goodsId,
        carModelMatchType,
        categoryCode,
        jekunModelCode
      })
      if (res.data.success) {
        let categoryItem = res.data.data
        categoryItem.categoryKey = Number(categoryKey)
        categoryItem.parentKey = Number(parentKey)
        let goodsItems: Array<any> = []
        for (let i in categoryItem.goodsItems) {
          if (Number(categoryItem.goodsItems[i].num) !== 0) {
            goodsItems.push(categoryItem.goodsItems[i])
          }
        }
        categoryItem.goodsItems = goodsItems
        await this.props.dispatchDiyList(categoryItem)
        Taro.navigateBack({
          delta: 1
        })
      }
    } catch (error) {
    } finally {
      Taro.hideLoading()
    }
  }

  render() {
    const scrollStyle = {
      height: '100vh'
    }
    let { goodsList, disabled } = this.state
    return (
      <View className='annual-diy-wrap'>
        <View className='btn-wrap'>
          <AtButton type='primary' disabled={disabled} onClick={this.handleSubmit.bind(this)}>确认提交</AtButton>
        </View>
        <ScrollView className='list' scrollWithAnimation enableBackToTop scrollY onScroll={this.onScroll.bind(this)} style={scrollStyle}>
          <View className='content-wrap'>

            {goodsList.map((goods, goodsIndex) =>
              <View className={
                classnames('item-info', {
                  'checked': goods.checked
                })
              } key={goods.goodsId} onClick={this.handleChecked.bind(this, goodsIndex)}
              >
                <View className='left'>
                  <Image className='annual-img' mode='aspectFill' lazyLoad src={goods.thumbnailUrl}></Image>
                </View>
                <View className='right'>
                  <Text className='goods-name'>{goods.goodsName}</Text>
                  <View className='r-bottom-wrap'>
                    <View className='r-bottom-t'>
                      {goods.tags && goods.tags.length && <View className='tag'>{goods.tags.join(',')}</View>}
                      <Text>已售出{goods.saleCount}件</Text>
                    </View>
                    <View className='r-bottom-b'>
                      <View className='r-bottom-b-r'>
                        ￥<Text className='price'>{Number(goods.annualCardPrice)}</Text>
                        <Text className='origin-price'>￥{goods.platformPrice}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            )}
          </View>
        </ScrollView>
        <AtMessage />
      </View>
    )
  }
}
